import React from "react";
import {Button, Checkbox, Form, Icon, Input, InputNumber, Rate, Select, Switch, Upload} from "antd";

import request, {get} from "@/axios/tools";

import {handleUpload, UploadList} from "@/components/form/UploadList";

const {Item: FormItem} = Form;
const {TextArea} = Input;
const {Group: CheckboxGroup} = Checkbox;
const {Option} = Select;


const previewFile = (file, callback) => {
    const reader = new FileReader();
    reader.onloadend = () => callback(reader.result);
    reader.readAsDataURL(file);
};


export class FoodForm extends React.Component {
    constructor(props) {
        super(props)
        this.form = this.props.form;
        // this.foodTypeList = this.props.foodTypeList || [];
        this.getFieldDecorator = this.form.getFieldDecorator;

        this.options = [];

        this.printerOptions = [];

        this.formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 14},
        };
        this.state = {
            foodTypeList: [],
            printerList: [],
            foodTypeCheckedDef: [],
            allowSingleDef: true,
            allowDiscount: true,
            hide: false,
            menus: [],
            fileList: [],
            uploading: false,
            removedFile: []
        }
    }

    updateReducePrice = () => {
        setTimeout(() => {
            this.form.setFieldsValue({'reducedPrice': this.form.getFieldValue('price')});
        }, 0)
    }


    handleSubmit = () => {
        this.form.validateFields('', {}, (errors, value) => {
            if (errors === null) {
                const {currentFood} = this.props;
                const {removedFile} = this.state;
                //   console.log(currentFood.id)
                if (removedFile.length) {
                    removedFile.forEach((item) => {
                        this._delFile(item.id);
                    })
                    this.setState({removedFile: []});
                }
                let id = currentFood && currentFood.id || 0;
                this.handleUpload(id);
                this._postFood({id});
            }
        })
    }

    setFieldValue = (currentFood) => {

        if (currentFood) {
            // console.log(currentFood)
            let fields = this.form.getFieldsValue();
            for (let key in fields) {
                fields[key] = currentFood[key];
            }
            this.form.setFieldsValue(fields);
            this.setState({
                allowSingleDef: currentFood.allowSingle,
                allowDiscount: currentFood.allowDiscount,
                hide: currentFood.hide
            });

            let {menus, printerList} = this.state;
            // 设置表单菜品类型
            let menuState = [];
            currentFood.foodTypeList.forEach((item, index) => {
                menus.forEach((val, i) => {
                    if (val.id === item.id) {
                        menuState.push(item.id);
                    }
                });
            });
            // 设置表单打印设备
            let printerState = [];
            currentFood.equipments.forEach((item, index) => {
                printerList.forEach((val, i) => {
                    if (val.id === item.id) {
                        printerState.push(item.id)
                    }
                })
            })
            // console.log(printerList)
            this.form.setFieldsValue({
                menus: menuState.slice(),
                printers: printerState.slice()
            });

            let imageFile = currentFood.images.map((item, i) => {
                if (item.uid) {
                    return item;
                }
                return {
                    'id': item.id,
                    'name': item.name || item.local,
                    'description': item.description,
                    'local': item.local,
                    'alias': item.alias,
                    'status': 'done',
                    'url': this.props.picPre + '/' + item.local
                }
            });

            this.setState({
                fileList: imageFile
            });
            // console.log(imageFile, this.props)
        }
    }

    // 查询该饭店菜单信息
    _requestMenus = () => {
        return new Promise((resolve, reject) => {
            get('/restaurant/listMenus/' + this.props.auth.data.restaurant).then(data => {
                this.setState({foodTypeList: data.list});
                resolve(data)
            }, (err) => {
                reject(err)
            });
        })

    };
    // 查询打印设备
    _requestPinter = () => {
        const {auth: {data: {restaurant: restaurantID}}} = this.props;
        return get('/restaurant/listEquipments', {restaurantID, type: 'PRINTER'})
            .then((data) => {
                this.setState({printerList: data})
            }, (err) => {
                console.log(err)
            })
    }

    /**
     *  上传菜品信息
     */
    _postFood = ({id = 0}) => {
        const {restaurant} = this.props.auth.data;
        let formValues = this.form.getFieldsValue();

        formValues.menus = formValues.menus.join(',');
        formValues.printers = formValues.printers.join(',');
        formValues.singleDiscount = formValues.singleDiscount || 0;
        if (!formValues.sellCount && formValues.sellCount !== 0) formValues.sellCount = '';
        request({
            url: '/food/item', method: 'post', params: {
                restaurantID: restaurant,
                id,
                allowSingle: true,
                ...formValues
            }
        }).then(data => {
            const {handleAfterSubmit} = this.props;
            data.menus = this.state.menus;
            data.fileList = this.state.fileList;
            handleAfterSubmit && handleAfterSubmit(data);
        });
    };

    /**
     *  删除菜品图片
     */
    _delFile = (id) => {
        request({url: '/food/itemPics/' + id, method: 'delete'}).then(data => {
            console.log(data);
        });
    };


    handlePreview = () => {

    };

    handleChange = (data) => {
        const {file} = data;
        const {fileList} = this.state;

        // file.status = 'done';
        if (!file.description) file.description = file.name;
        if (!file.local) {
            file.local = file.name;
        }
        if (!file.url) {
            previewFile(file.originFileObj, (previewDataUrl) => {
                file.url = previewDataUrl;
                this.forceUpdate();
            })
        }

        // 添加文件显示在顶部
        fileList.unshift(file);
        this.setState({fileList: fileList.slice()});
    }

    handleUpload = (id) => {
        // uploadList 上传文件
        handleUpload(id, this.state);
    }

    updateFileList = (data, key) => {
        key = key || 'fileList';
        this.setState({[key]: data})
    }

    handleCustomReq = () => {
    }


    render() {
        const {formItemLayout, getFieldDecorator, setFieldValue, handleRemoveFile, handleUpdateDes} = this;
        const {foodTypeList, printerList, foodTypeCheckedDef, allowSingleDef, allowDiscount, fileList, hide} = this.state;

        this.options = [];
        this.printerOptions = [];

        foodTypeList.forEach((item, index) => {
            this.options.push({label: item.name, value: item.id});
        })

        printerList.forEach((printer) => {
            this.printerOptions.push({label: printer.alias, value: printer.id});
        })
        const uploadButton = (
            <div>
                <Icon type="plus"/>
                <div className="ant-upload-text">Upload</div>
            </div>
        );

        return (
            <Form>
                <FormItem
                    {...formItemLayout}
                    label="菜品名称"
                >
                    {getFieldDecorator('name', {
                        rules: [{
                            required: true, message: '请输入菜品名称!',
                        }],
                        initialValue: ''
                    })(
                        <Input placeholder="请输入菜名"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="菜品价格(￥)"

                >
                    {getFieldDecorator('price', {
                        rules: [{type: 'number', message: '格式不正确！'}, {
                            required: true, message: '请输入菜品价格!',
                        }]
                    })(
                        <InputNumber
                            placeholder="请输入菜品价格"
                            formatter={value => `${value}`}
                            parser={value => value.replace('￥', '')}
                            style={{width: '100%'}}
                            onChange={this.updateReducePrice}
                            min={0}
                        />
                    )}


                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="菜品优惠价格(￥)"
                >
                    {getFieldDecorator('reducedPrice', {
                        rules: [{type: 'number', message: '格式不正确！'}, {
                            required: true, message: '请输入优惠价格!',
                        }]
                    })(
                        <InputNumber
                            placeholder="请输入菜品价格"
                            formatter={value => `${value}`}
                            parser={value => value.replace('￥', '')}
                            style={{width: '100%'}}
                            min={0}
                        />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="菜品状态"
                >
                    {getFieldDecorator('status', {
                        rules: [{
                            required: true, message: '请输入优惠价格!',
                        }],
                        initialValue: "ENABLE"
                    })(
                        <Select >
                            <Option value="ENABLE">上架</Option>
                            <Option value="SELL_OUT">售罄</Option>
                            <Option value="DISABLE">下架</Option>
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="每日数量限制"
                >
                    {getFieldDecorator('sellCount', {
                        rules: [],
                        initialValue: ''
                    })(
                        <InputNumber style={{width: '100%'}} placeholder={'不填写则不限制数量'}/>
                    )}
                    {/*<Switch/>*/}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="菜品描述"
                >
                    {getFieldDecorator('description', {
                        rules: [],
                        initialValue: ''
                    })(
                        <TextArea rows={4}/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="菜品类型"
                >
                    {getFieldDecorator('menus', {
                        rules: [{
                            required: true, message: '请选择菜品类型!',
                        }],
                        initialValue: foodTypeCheckedDef
                    })(
                        <CheckboxGroup options={this.options}/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="打印区域"
                >
                    {getFieldDecorator('printers', {
                        rules: [{
                            required: true, message: '请选择打印区域!',
                        }],
                        initialValue: this.printerOptions.map((printer) => {
                            return printer.value;
                        })
                    })(
                        <CheckboxGroup options={ this.printerOptions }/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="评分"
                >
                    {getFieldDecorator('score', {
                        rules: [{
                            required: true, message: '请选择评分!',
                        }],
                        initialValue: 5
                    })(
                        <Rate />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="菜品单独折扣(%)"

                >
                    {getFieldDecorator('singleDiscount', {
                        rules: [{type: 'number', message: '格式不正确！'}, {
                            required: false, message: '',
                        }]
                    })(
                        <InputNumber
                            placeholder="不填或者0表示不使用单独折扣"
                            style={{width: '100%'}}
                            min={0}
                            max={100}
                        />
                    )}


                </FormItem>

                <FormItem
                    {...formItemLayout}
                    label="是否参与打折"
                >
                    {getFieldDecorator('allowDiscount', {
                        rules: [{
                            required: true, message: '请选择是否使参与打折!',
                        }],
                        initialValue: allowDiscount
                    })(
                        <Switch checked={allowDiscount} onClick={() => {
                            this.setState({allowDiscount: !allowDiscount})
                        }} checkedChildren="是" unCheckedChildren="否"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="是否隐藏"
                >
                    {getFieldDecorator('hide', {
                        rules: [{
                            required: false, message: '',
                        }],
                        initialValue: hide
                    })(
                        <Switch checked={hide} onClick={() => {
                            this.setState({hide: !hide})
                        }} checkedChildren="是" unCheckedChildren="否"/>
                    )}
                </FormItem>


                {
                    this.props.showUpload &&
                    <FormItem {...formItemLayout} label="图片上传" wrapperCol={{span: 14}}>
                        <div className="clearfix">
                            <Upload
                                fileList={fileList}
                                onPreview={this.handlePreview}
                                onChange={this.handleChange}
                                onRemove={this.handleRemove}
                                customRequest={this.handleCustomReq}
                                showUploadList={false}
                            >
                                {fileList.length < 2 ? (
                                    <Button>
                                        <Icon type="upload"/> upload
                                    </Button>
                                ) : ''}
                            </Upload>
                            <UploadList fileList={fileList} state={this.state} updateFileList={this.updateFileList}/>
                        </div>

                    </FormItem>
                }
                <FormItem wrapperCol={{span: 12, offset: 6}}>
                    <Button type="primary" onClick={this.handleSubmit}>提交</Button>
                </FormItem>
            </Form>
        )
    }

    componentDidMount() {
        this._requestMenus()
            .then((data) => {
                this.setState({menus: data.list})
                this._requestPinter()
                    .then(() => {
                        const {currentFood} = this.props;
                        this.setFieldValue(currentFood)
                    })
            })
    }
}                  
                   